 package com.itic.market.mobile.tixian;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.market.mobile.base.BaseMobileInterface;
import com.itic.market.system.tixian.persistence.model.Tixian;
import com.itic.market.system.tixian.persistence.model.TixianExample;
import com.itic.market.system.tixian.persistence.model.TixianExample.Criteria;
import com.itic.market.system.tixian.service.TixianService;
import com.itic.market.system.user.persistence.model.MarketUser;
/**
 * 友惠家商城中心接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/tixian")
public class MarketTixianInterface
     extends BaseMobileInterface {
	
	protected static final String MUST_ONE_MONEY_ERROR_MSG = "提现金额必段大于";
	@Autowired
	private TixianService tixianService;
	
	@RequestMapping(value="/history")
    @ResponseBody
	public Map<String,Object> history( HttpServletRequest request,HttpServletResponse response, String token){
		Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
		//判断必要的参数
		if( StringHelper.isNotBlank(token) ){
			//减少用户的账户金额
			MarketUser user = getMarketUserByToken(token);
			if( null != user ){
				TixianExample example = new TixianExample();
				example.setOrderByClause("CREATE_TIME DESC");
				Criteria criteria = example.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andIsGiveEqualTo(DBConst.TRUE);
				criteria.andUserIdEqualTo(user.getId());
				List<Tixian> list = tixianService.list(example);
				resultMap.put(DATA, list);
				result = SUCCESS;
				errorCode = SUCCESS_ERROR_CODE;
		    	errorMsg = SUCCESS_ERROR_MSG;
			}else{
				result = LOGIN;
				errorCode = LOGIN_ERROR_CODE;
		    	errorMsg = LOGIN_ERROR_MSG;
			}
		}
		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	
	@RequestMapping(value="/add")
    @ResponseBody
	public Map<String,Object> add( HttpServletRequest request,HttpServletResponse response, String token, String name, String account, String money, String actureName ){
		Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
		//判断必要的参数
		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(money) && StringHelper.isNotBlank(name) && StringHelper.isNotBlank(account) ){
			//减少用户的账户金额
			MarketUser user = getMarketUserByToken(token);
			if( null != user ){
				
				BigDecimal   b   =   new   BigDecimal(money);  
				money = b.setScale(2,   BigDecimal.ROUND_HALF_UP).toString();
				
				String setting = sysSettingService.getByKey("USER_TIXIAN_MONEY");
				//判断用户金额 是否大于提现金额
				boolean greater = NumberStringHelper.isGreater(money, setting);
				if( greater ){
					String fee = "0.5";
					String first = isFirst(user);
					if(!"first".equals(first)){
						String feeSet = sysSettingService.getByKey("TIXIAN_FEE");
						if( StringHelper.isNotBlank(feeSet)){
							fee = feeSet;
						}
					}else{
						fee="0";
					}
					
					String totalMoney = NumberStringHelper.subtractString(money, fee);//扣除手续费用的金额
					
					if( NumberStringHelper.isGreater(user.getMoney(), money) ){
						
						String times = getTimes(user);
						
						result = addTixian(user,totalMoney,fee,times,name,account,actureName);
						
						errorCode = SUCCESS_ERROR_CODE;
				    	errorMsg = SUCCESS_ERROR_MSG;
				    	
					}else{
						result = FAIL;
						errorCode = LESS_MONEY_ERROR_CODE;
						errorMsg = LESS_MONEY_ERROR_MSG ;
						if( NumberStringHelper.isGreaterNoEqual(fee, "0")){
							errorMsg = LESS_MONEY_ERROR_MSG + ",提现手续费用"+fee+"元！";
						}
		            	
					}
				}else{
					result = FAIL;
					errorCode = MUST_ONE_MONEY_ERROR_CODE;
	            	errorMsg = MUST_ONE_MONEY_ERROR_MSG +setting+ "元！";
				}
			}else{
				result = LOGIN;
				errorCode = LOGIN_ERROR_CODE;
		    	errorMsg = LOGIN_ERROR_MSG;
			}
			
		}
		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	
	
	
	/*@RequestMapping(value="/add")
    @ResponseBody
	public Map<String,Object> add( HttpServletRequest request,HttpServletResponse response, String token, String name, String account, String money ){
		Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
		//判断必要的参数
		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(money) && StringHelper.isNotBlank(name) && StringHelper.isNotBlank(account) ){
			//减少用户的账户金额
			MarketUser user = getMarketUserByToken(token);
			if( null != user ){
				String setting = sysSettingService.getByKey("USER_TIXIAN_MONEY");
				//判断用户金额 是否大于提现金额
				boolean greater = NumberStringHelper.isGreater(money, setting);
				if( greater ){
					String fee = "0.5";
					String first = isFirst(user);
					if(!"first".equals(first)){
						String feeSet = sysSettingService.getByKey("TIXIAN_FEE");
						if( StringHelper.isNotBlank(feeSet)){
							fee = feeSet;
						}
					}else{
						fee="0";
					}
					
					String totalMoney = NumberStringHelper.addString(money, fee);
					
					if( NumberStringHelper.isGreater(user.getMoney(), totalMoney) ){
						
						String times = getTimes(user);
						
						result = addTixian(user,money,fee,times,name,account);
						
						errorCode = SUCCESS_ERROR_CODE;
				    	errorMsg = SUCCESS_ERROR_MSG;
				    	
					}else{
						result = FAIL;
						errorCode = LESS_MONEY_ERROR_CODE;
						errorMsg = LESS_MONEY_ERROR_MSG ;
						if( NumberStringHelper.isGreaterNoEqual(fee, "0")){
							errorMsg = LESS_MONEY_ERROR_MSG + ",提现手续费用"+fee+"元！";
						}
		            	
					}
				}else{
					result = FAIL;
					errorCode = MUST_ONE_MONEY_ERROR_CODE;
	            	errorMsg = MUST_ONE_MONEY_ERROR_MSG +setting+ "元！";
				}
			}else{
				result = LOGIN;
				errorCode = LOGIN_ERROR_CODE;
		    	errorMsg = LOGIN_ERROR_MSG;
			}
			
		}
		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}*/
	
	public String getTimes(MarketUser user){
		String result = "0";
		if( null != user ){
		   String id = user.getId();
		   TixianExample example = new TixianExample();
		   example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andIsGiveEqualTo("1").andUserIdEqualTo(id);
		   List<Tixian> list = tixianService.list(example);
		   int size = list.size();
		   size++;
		   result = size+"";
		}
		return result;
	}
	
	public String addTixian( MarketUser user, String money , String fee , String times, String name,String account,String actureName ){
		String result="";
		//添加提现记录信息表数据
		Tixian tixian = new Tixian();
		tixian.setMoney(money);
		tixian.setFeeMoney(Double.parseDouble(fee));
		tixian.setTimes(Integer.parseInt(times));
		tixian.setId(IdGen.uuid());
		tixian.setIsEffective(DBConst.TRUE);
		tixian.setCreateUser(CREATE_USER);
		tixian.setOrgCode(ORG_CODE);
		tixian.setCreateTime(new Date());
		tixian.setUpdateTime(new Date());
		
		tixian.setUserId(user.getId());
		tixian.setUserName( filterEmoji(user.getUserNickName()) );
		if(StringHelper.isBlank(user.getUserHeadImg())){
			user.setUserHeadImg("http://file.jhjvip.cn/images/default.jpg");
		}
		tixian.setUserHeadImg(user.getUserHeadImg());
		tixian.setType("支付宝");
		tixian.setIsGive("0");
		tixian.setZfbName(name);
		tixian.setZfbAccount(account);
		tixian.setActureName(actureName);
		String kouMoney = NumberStringHelper.addString(money, fee);
		String userMoney = NumberStringHelper.subtractString(user.getMoney(), kouMoney);
		user.setMoney(userMoney);
		
	    result = marketUserService.tixianCreate( user, tixian );
		//添加手机提醒
		String phoneMail = sysSettingService.getByKey("TIXIAN_PHONE_MAIL");
		String phone = "18600560770";
		String mail = "491368175@qq.com";
		if( StringHelper.isNotBlank(phoneMail) ){
			String[] split = phoneMail.split(",");
			
			phone=split[0];
			mail=split[1];
			
		}
		sendTixianMsg(phone, name, money);
		String content = "微信用户《"+user.getUserNickName()+"》申请提现"+money+"元到支付宝账号"+name+"，请及时处理！时间："+DateHelper.getDate();
		sendMailMsg(mail,content);
		
		return result;
	}
	
	
	public String isFirst( MarketUser user ){
		String result = "notFirst";
		if( null != user ){
		   String id = user.getId();
		   TixianExample example = new TixianExample();
		   example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andIsGiveEqualTo("1").andUserIdEqualTo(id);
		   List<Tixian> list = tixianService.list(example);
		   if( list.size() == 0 ){
			   result = "first";
		   }
		}
		return result;
	}
	
	/**
	 * 是否第一次申请
	 * @param request
	 * @param response
	 * @param token
	 * @return
	 */
    @RequestMapping(value="/isFirst")
    @ResponseBody
	public Map<String,Object> isFirst( HttpServletRequest request,HttpServletResponse response, String token){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) ){
            	MarketUser user = getMarketUserByToken(token);
    			if( null != user ){
    				resultMap.put(DATA, isFirst(user));
    				result = SUCCESS;
    				errorCode = SUCCESS_ERROR_CODE;
    		    	errorMsg = SUCCESS_ERROR_MSG;
    			}else{
    				result = LOGIN;
    				errorCode = LOGIN_ERROR_CODE;
    		    	errorMsg = LOGIN_ERROR_MSG;
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	
    @RequestMapping(value="/test")
	@ResponseBody
	public void test(){
		sendTixianMsg("18401762162","xxb","10");
	}
    
    /**
     * 用户提现到支付宝或微信成功的回调接口
     * @param request
     * @param response
     * @param token
     * @param products
     * @return
     */
    @RequestMapping(value="/list")
    @ResponseBody
    public Map<String,Object> list( HttpServletRequest request,HttpServletResponse response, String token){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) ){
            	MarketUser user = getMarketUserByToken(token);
    			if( null != user ){
    				Map<String, Object> dataMap = new HashMap<String,Object>();
    				TixianExample example = new TixianExample();
    				example.setOrderByClause("CREATE_TIME DESC");
    				Criteria criteria = example.createCriteria();
    				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    				criteria.andUserIdEqualTo(user.getId());
    				this.handlePageQuery(request, example);
    				
    				int count = tixianService.count(example);
    				List<Tixian> list = tixianService.list(example);
    				dataMap.put("list", list);
    				dataMap.put("count", count);
    				resultMap.put(DATA, dataMap);
    				result = SUCCESS;
    				errorCode = SUCCESS_ERROR_CODE;
    		    	errorMsg = SUCCESS_ERROR_MSG;
    			}else{
    				result = LOGIN;
    				errorCode = LOGIN_ERROR_CODE;
    		    	errorMsg = LOGIN_ERROR_MSG;
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
}